package api;

import cn.hutool.json.JSONUtil;
import comment.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import model.UserInfo;
import util.DBUtil;
import util.SessionUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/deldish")
public class DelDishServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int state = -1;
        String msg = "未知错误";
        int data = 0;

        //验证登录信息
        UserInfo userInfo = SessionUtil.getSessionUserInfo(req);
        if(userInfo != null){
            Integer did = Integer.parseInt(req.getParameter("did"));
            if(did != null && did > 0){
                //参数传递正确
                Connection connection = DBUtil.getConnection();
                String sql = "update dish set isdown=1 where did=?";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1,did);
                data = statement.executeUpdate();
                state = data > 0 ? 200 : -1;

            }
            else {
                msg = "参数错误";
            }
        }
        else {
            msg = "未登录！";
        }


        resp.setContentType(ApplicationVariable.APPLICATION_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(state,data,msg)));
    }
}
